//package com.hundun.vision.biz.robot;
//
//import com.hundun.vision.biz.OrderDTO;
//import com.hundun.vision.biz.dto.WalletDTO;
//import com.hundun.vision.biz.dao.TradeDetailDAO;
//import com.hundun.vision.biz.dto.KlineBarDTO;
//import com.hundun.vision.biz.po.TradeDetailPO;
//import com.hundun.vision.biz.request.KlineRequest;
//import com.hundun.vision.biz.service.MarketService;
//import com.hundun.vision.biz.utils.TimeUtils;
//import org.apache.commons.collections.CollectionUtils;
//import org.ta4j.core.Bar;
//import org.ta4j.core.BarSeries;
//import org.ta4j.core.BaseBar;
//import org.ta4j.core.Strategy;
//
//import java.math.BigDecimal;
//import java.time.Duration;
//import java.time.Instant;
//import java.time.ZoneId;
//import java.time.ZonedDateTime;
//import java.util.List;
//
///**
// * @author ：RuoChen
// * @date ：14:06 2024/3/1
// * @description：量化机器人
// */
//public class Bot implements Runnable {
//    private String symbol;
//    private String interval;
//    private BarSeries series;
//    private Strategy strategy;
//
//    private BigDecimal weight;
//
//    /**
//     * 当前订单状态：0=未交易 1=买入 2=卖出
//     */
//    private Integer currentStatus = 0;
//
//    private static final String BUY = "BUY";
//    private static final String SELL = "SELL";
//    private static final String MONEY = "USDT";
//
//    private static final BigDecimal feeRate = BigDecimal.valueOf(0.0002);
//
//    private MarketService marketService;
//
//    private TradeDetailDAO tradeDetailDAO;
//
//    public Robot(String symbol, String interval,BigDecimal weight, BarSeries series, Strategy strategy, MarketService marketService, TradeDetailDAO tradeDetailDAO) {
//        this.symbol = symbol;
//        this.interval = interval;
//        this.weight = weight;
//        this.series = series;
//        this.strategy = strategy;
//        this.marketService = marketService;
//        this.tradeDetailDAO = tradeDetailDAO;
//    }
//
//    @Override
//    public void run() {
//        TradeDetailPO latestTrade = tradeDetailDAO.getBySymbol(symbol, null);
//        if (latestTrade != null) {
//            String side = latestTrade.getSide();
//            if (BUY.equals(side)) {
//                currentStatus = 1;
//            } else {
//                currentStatus = 2;
//            }
//        } else {
//            currentStatus = 0;
//        }
//        while (true) {
//            updateBarSeries();
//            WalletDTO wallet = marketService.getWallet();
//            if (wallet != null) {
//                if (currentStatus != 1 && shouldBuy()) {
//                    BigDecimal balance = wallet.getBalance(MONEY);
//                    //todo:基于配置计算购买数量
//                    BigDecimal quantity = balance;
//                    createBuyOrder(wallet);
//                    currentStatus = 1;
//                }
//                if (currentStatus == 1 && shouldSell()) {
//                    createSellOrder(wallet);
//                    currentStatus = 2;
//                }
//            }
//        }
//    }
//
//    /**
//     * 更新BarSeries中最后一个Bar的数据
//     */
//    public void updateBarSeries() {
//        KlineRequest request = new KlineRequest();
//        request.setSymbol(symbol);
//        request.setInterval(interval);
//        request.setLimit(1);
//        List<KlineBarDTO> klineBars = marketService.getKlineBar(request);
//        if (CollectionUtils.isNotEmpty(klineBars)) {
//            KlineBarDTO latestKlineBar = klineBars.get(0);
//            Duration barDuration = Duration.ofSeconds(TimeUtils.getDuration(interval));
//            ZonedDateTime endTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(latestKlineBar.getEndTimestamp()), ZoneId.systemDefault());
//            Bar latestBar = new BaseBar(barDuration, endTime, latestKlineBar.getOpen(), latestKlineBar.getHigh(), latestKlineBar.getLow(), latestKlineBar.getClose(), latestKlineBar.getVol(), latestKlineBar.getAmount());
//            series.addBar(latestBar, true);
//        }
//    }
//
//    /**
//     * 检查是否满足买入规则
//     *
//     * @return
//     */
//    public boolean shouldBuy() {
//        return strategy.shouldEnter(series.getEndIndex());
//    }
//
//    /**
//     * 检查是否满足卖出规则
//     *
//     * @return
//     */
//    public boolean shouldSell() {
//        return strategy.shouldExit(series.getEndIndex());
//    }
//
//    /**
//     * 下单执行买入操作
//     *
//     * @param wallet
//     */
//    public void createBuyOrder(WalletDTO wallet) {
//        BigDecimal quantity=BigDecimal.ZERO;
//        BigDecimal balance = wallet.getBalance(MONEY);
////        balance.divide()
////        double premiumBuyQuantity = amount / ((1 + feeRate) * buyPrice);
////        BigDecimal.valueOf(premiumBuyQuantity).setScale(symbolDTO.getQuantity_scale(), BigDecimal.ROUND_DOWN).toPlainString();
//        OrderDTO order = marketService.createOrder(symbol, BUY, quantity);
//        if (order != null) {
//            TradeDetailPO tradeDetailPO = new TradeDetailPO();
//            tradeDetailPO.setSymbol(symbol);
//            tradeDetailPO.setOrderId(String.valueOf(order.getOrderId()));
//            tradeDetailPO.setSide(BUY);
//            tradeDetailPO.setQuantity(quantity);
//            tradeDetailPO.setPrice(new BigDecimal(order.getPrice()));
//            tradeDetailDAO.insert(tradeDetailPO);
//        }
//    }
//
//    /**
//     * trade_detail
//     * 下单执行卖出操作
//     *
//     * @param wallet
//     */
//    public void createSellOrder(WalletDTO wallet) {
//        String coin = symbol.substring(0, symbol.indexOf(MONEY));
//        BigDecimal quantity = wallet.getBalance(coin);
//        OrderDTO order = marketService.createOrder(symbol, SELL, quantity);
//        if (order != null) {
//            TradeDetailPO latestBuyTrade = tradeDetailDAO.getBySymbol(symbol, BUY);
//            BigDecimal buyAmount = latestBuyTrade.getAmount();
//            BigDecimal sellAmount = new BigDecimal(order.getCummulativeQuoteQty());
//            TradeDetailPO tradeDetailPO = new TradeDetailPO();
//            tradeDetailPO.setSymbol(symbol);
//            tradeDetailPO.setOrderId(String.valueOf(order.getOrderId()));
//            tradeDetailPO.setSide(SELL);
//            tradeDetailPO.setQuantity(quantity);
//            tradeDetailPO.setPrice(new BigDecimal(order.getPrice()));
//            tradeDetailPO.setAmount(sellAmount);
//            BigDecimal profit = sellAmount.subtract(buyAmount);
//            tradeDetailPO.setProfit(profit);
//            BigDecimal profitPercentage = profit.divide(buyAmount, 2, BigDecimal.ROUND_HALF_UP)
//                    .multiply(new BigDecimal("100"));
//            tradeDetailPO.setProfitRatio(profitPercentage);
//            tradeDetailDAO.insert(tradeDetailPO);
//        }
//    }
//}
